﻿using System;
using System.Collections.Generic;
using System.IO;
using EnvDTE;
using EnvDTE80;
using Calimbra.Addin.Messages;

namespace Calimbra.Addin.Functions
{
    class Create_files
    {
        private DTE2 dte;
        public void Process(List<FunctionUnit> function_units)
        {
            SelectedItem selectedItem = dte.SelectedItems.Item(1);
            ProjectItem fdfFile = selectedItem.ProjectItem;
            var containingProject = fdfFile.ContainingProject;
            foreach (FunctionUnit functionUnit in function_units)
            {
                ProjectItem funtionUnitItem = null;
               
                foreach (ProjectItem projectItem in containingProject.ProjectItems)
                {
                    if (projectItem.Name == functionUnit.Name+".cs")
                    {
                        funtionUnitItem = projectItem;
                        break;
                    }
                }
                if (funtionUnitItem == null)
                {
                    //if not in solution but file exists
                    var projectFile = new FileInfo(containingProject.FileName);
                    var fileToCreate = new FileInfo(Path.Combine(projectFile.Directory.FullName, functionUnit.Name + ".cs"));
                    
                    ProjectItem projectItem = dte.Solution.FindProjectItem(fileToCreate.Name);
                    if (projectItem == null)
                    {
                        if (fileToCreate.Exists)
                            fileToCreate.Delete();
                        fileToCreate.Create();
                        containingProject.ProjectItems.AddFromFile(fileToCreate.FullName);
                    }
                }
            }
        }

        public void Inject(DTE2 dte2)
        {
            dte = dte2;
        }
    }
}
